package com.hp.java11_springboot_mp_vue_elementui.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hp.java11_springboot_mp_vue_elementui.entity.JsonResult;
import com.hp.java11_springboot_mp_vue_elementui.entity.SProduct;
import com.hp.java11_springboot_mp_vue_elementui.service.ISProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 */
@RestController
public class SProductController {

    @Autowired
    private ISProductService productService;

    @RequestMapping(value = "/products",method = RequestMethod.GET)
    public JsonResult pageProducts(@RequestParam(value = "current",required = false,defaultValue = "1")
                                               Integer current){
        try {
            IPage<SProduct> arg = new Page<>(current, 10);
            IPage<SProduct> page = productService.pageProducts(arg);
            return new JsonResult(1, page);
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(0,null);
        }
    }

    @PostMapping("/product")
    public JsonResult saveProduct(@RequestBody SProduct product){
        try {
            product.setId(UUID.randomUUID().toString().substring(0,10));
            product.setCreateTime(LocalDateTime.now());
            productService.save(product);
            return new JsonResult(1, product);
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(0,null);
        }
    }

    @PutMapping("/product")
    public JsonResult updateProduct(@RequestBody SProduct product){
        try {
            product.setCreateTime(LocalDateTime.now());
            productService.updateById(product);
            return new JsonResult(1, product);
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(0,null);
        }
    }

    @DeleteMapping("/product/{id}")
    public JsonResult updateProduct(@PathVariable("id")String id){
        try {
            productService.removeById(id);
            return new JsonResult(1, null);
        }catch (Exception ex){
            ex.printStackTrace();
            return new JsonResult(0,null);
        }
    }
}
